package com.yml.mall.interceptor;

import com.yml.mall.currentexception.MyException;
import com.yml.mall.enums.ResponseEnum;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @ClassName PathParamInterceptor
 * @Author Administrator
 * @Date 2020/4/9   13:49
 */
public class PathParamInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //取路径的参数
        Map pathVariables = (Map) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
        if(pathVariables==null) return super.preHandle(request, response, handler);
        if(pathVariables.get("id")!=null){
            //正则匹配是否为正整数（不加+(正)号）
            if(!pathVariables.get("id").toString().matches("^[0-9]+$")){
                System.out.println(pathVariables.get("id"));
                throw new MyException(ResponseEnum.PATH_PARAM_ERROR);
            }
        }
        //匹配productId
        if(pathVariables.get("productId")!=null){
            if(!pathVariables.get("productId").toString().matches("^[0-9]+$")){
                System.out.println(pathVariables.get("productId"));
                throw new MyException(ResponseEnum.PATH_PARAM_ERROR);
            }
        }
        return super.preHandle(request, response, handler);
    }
}
